<template>
  <div>
    <div class="search">
      <input type="text"
             class="input_search"
             v-model="keyword"
             placeholder="输入城市名或者拼音">
    </div>
    <div class="search-content"
         v-show="this.keyword">
      <ul>
        <li class="search-content-li border-bottom"
            v-for="item of this.list"
            :key="item.id"
            @click="handleCityClick(item.name);">{{item.name}}</li>
        <li v-show="showWhenNoData"
            class="search-content-li border-bottom">
          未找到相关匹配信息
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import { mapActions } from "vuex";
export default {
  name: "citySearch",
  data() {
    return {
      keyword: "",
      list: [],
      timer: null
    };
  },
  props: {
    cities: Object
  },
  computed: {
    showWhenNoData() {
      if (this.list.length) {
        return false;
      }

      return true;
    }
  },
  methods: {
    handleCityClick(city) {
      //this.$store.dispatch("changeCity", city); //dispatch到actions，然后actions中的changeCity再commit到mutations
      //this.$store.commit("changeCity", city)    直接使用commit提交到mutations也是可以的
      this.changeCity(city);
      this.$router.push({ path: "/" });
    },
    ...mapActions(["changeCity"])
  },
  watch: {
    //监控keyword并进行函数截流
    keyword() {
      if (this.timer) {
        clearTimeout(this.timer);
      }

      this.timer = setTimeout(() => {
        const result = [];

        if (!this.keyword) {
          this.list = [];
          return;
        }

        for (let i in this.cities) {
          this.cities[i].forEach(item => {
            if (
              item.spell.indexOf(this.keyword) > -1 ||
              item.name.indexOf(this.keyword) > -1
            ) {
              result.push(item);
            }
          });
        }

        this.list = result;
      }, 100);
    }
  }
};
</script>

<style lang="stylus" scoped>
@import ('~styles/varibles.styl');

.search {
  height: 0.72rem;
  line-height: 0.72rem;
  background-color: $bgColor;
  padding: 0.1rem;

  .input_search {
    width: 100%;
    height: 0.62rem;
    line-height: 0.62rem;
    border-radius: 0.1rem;
    font-size: 0.15rem;
    text-align: center;
    color: #666;
    box-sizing: border-box;
    padding: 0 0.1rem;
  }
}

.search-content {
  z-index: 1;
  overflow: hidden;
  position: absolute;
  top: 1.78rem;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ddd;

  .search-content-li {
    line-height: 0.62rem;
    background-color: #fff;
    text-align: left;
    padding-left: 0.1rem;
  }
}
</style>
